const db = require('../db/index')
const _ = require('lodash')
    // 获取树状结果
function getTreeResult(keyCate, cate, type) {
    var result = []
    for (idx in cate) {
        var cat = cate[idx]
        if (cat.cat_level == 0) {
            // 一级分类
            result.push(cat)
        } else {
            if (cat.cat_level >= type) continue
            var parentCate = keyCate[cat.cat_pid]
            if (!parentCate) continue
            if (!parentCate.children) {
                parentCate['children'] = []
            }
            parentCate.children.push(cat)
        }
    }
    return result
}
// 添加分类
exports.addCategories = (req, res) => {
        // console.log(123);
        // 1.获取数据
        var cat_pid = req.body.cat_pid
        var cat_name = req.body.cat_name
        var cat_level = req.body.cat_level
            // console.log(cat_name);
            //2.检查分类名称是否存在
        var sql = "select * from sp_category where cat_name=?"
        db.query(sql, cat_name, (err, result) => {
            if (err) return res.ResData("添加失败")
            if (result.length > 0) {
                return res.ResData("分类已经存在")
            }
            // 3.添加数据
            var sql = "insert into sp_category(cat_pid,cat_name,cat_level) values(?,?,?)"
            db.query(sql, [cat_pid, cat_name, cat_level], (err, results) => {
                if (err) return res.ResData('添加失败')
                res.ResData("创建成功", 200, {
                    "cat_name": cat_name,
                    "cat_pid": cat_pid,
                    "cat_level": cat_level
                })
            })
        })
    }
    // 根据 id 查询分类
exports.search = (req, res) => {
        // 1.接收参数
        var id = req.params.id
            // 2.查询信息
        var sql = "select * from sp_category where cat_id=?"
        db.query(sql, id, (err, result) => {
            if (err) return res.ResData("查询失败！")
            if (result.length > 0) {
                // 3.返回结果
                res.ResData("获取成功", 200, {
                    "cat_id": result[0].cat_id,
                    "cat_name": result[0].cat_name,
                    "cat_pid": result[0].cat_pid,
                    "cat_level": result[0].cat_level
                })
            } else {
                res.ResData('查询失败！')
            }
        })
    }
    // 编辑提交分类
exports.update = (req, res) => {
        // 1.接收数据
        var id = req.params.id
        var cat_name = req.body.cat_name
            // 2.更新数据
        var sql = "update sp_category set cat_name=? where cat_id=?"
        db.query(sql, [cat_name, id], (err, result) => {
            if (err) return res.ResData('更新失败')
            if (result.affectedRows < 1) {
                return res.ResData('更新失败')
            }
            // 3.查询数据
            var sql = "select * from sp_category where cat_id=?"
            db.query(sql, id, (err, results) => {
                res.ResData('更新成功', 200, {
                    "cat_id": results[0].cat_id,
                    "cat_name": results[0].cat_name,
                    "cat_pid": results[0].cat_pid,
                    "cat_level": results[0].cat_level
                })
            })
        })
    }
    // 删除分类
exports.delete = (req, res) => {
        // 1.获取数据
        var id = req.params.id
            // 2.根据ID删除数据
        var sql = "delete  from sp_category where cat_id=?"
        db.query(sql, id, (err, result) => {
            if (err) return res.ResData('删除失败')
            if (result.affectedRows != 1) return res.ResData('删除失败')
            res.ResData('删除成功', 200)
        })
    }
    // 商品分类数据列表
exports.getCategories = (req, res) => {
        // console.log(123);
        // 获取数据
        var type = req.query.type
        var pagenum = req.query.pagenum
        var pagesize = req.query.pagesize
        var sql = "select * from sp_category"
        db.query(sql, (err, result) => {
            if (err) return res.ResData('获取失败！')
            var keyCate = _.keyBy(result, 'cat_id')
            if (!type) type = 3
            var resultData = getTreeResult(keyCate, result, type)
            if (pagenum && pagesize) {
                count = resultData.length
                pagenum = parseInt(pagenum)
                pagesize = parseInt(pagesize)
                data = _.take(_.drop(resultData, (pagenum - 1) * pagesize), pagesize)
                data = {
                    "total": count,
                    "pagenum": pagenum,
                    "pagesize": pagesize,
                    "data": data
                }
                return res.ResData('获取成功', 200, data)
            }
            res.ResData('获取成功', 200, resultData)
        })
    }
    // 删除参数
exports.cateDelete = (req, res) => {
        // console.log(123);
        var id = req.params.id
        var attrId = req.params.attrId
            // console.log(attrid);
        var sql = "DELETE FROM sp_attribute WHERE cat_id=? AND attr_id=?"
        db.query(sql, [id, attrId], (err, result) => {
            if (err) return res.ResData('删除失败')
            if (result.affectedRows != 1) return res.ResData('删除失败')
            res.ResData('删除成功', 200)
        })
    }
    // 根据 ID 查询参数
exports.cateSearch = (req, res) => {
        // console.log(123);
        var id = req.params.id
        var attrId = req.params.attrId
        var attrSel = req.body.attr_sel
        var attrVals = req.body.attr_vals
        var sql = "select * from sp_attribute where cat_id=? AND attr_id=?"
        db.query(sql, [id, attrId], (err, result) => {
                if (err) return res.ResData('获取参数失败')
                console.log(result);
                res.ResData('获取成功', 200, {
                    "attr_id": attrId,
                    "attr_name": result[0].attr_name,
                    "cat_id": id,
                    "attr_sel": result[0].attr_sel,
                    "attr_write": result[0].attr_write,
                    "attr_vals": result[0].attr_vals
                })
            })
            // console.log(attrSel);
            // var sql = "select * from sp_attribute where"
    }
    // 编辑提交参数
exports.cateUpdate = (req, res) => {
        // console.log(12);
        var id = req.params.id
        var attrId = req.params.attrId
        var attrName = req.body.attr_name
        var attrSel = req.body.attr_sel
        var attrVals = req.body.attr_vals
            // console.log(attrSel);
        if (!attrVals) {
            var sql = "update sp_attribute set attr_name=?,attr_sel=?,attr_vals=''where cat_id=? AND attr_id=?"
            db.query(sql, [attrName, attrSel, id, attrId], (err, result) => {
                if (err) return res.ResData('更新失败')
                if (result.affectedRows < 1) {
                    return res.ResData('更新失败')
                }
                var sql = "select * from sp_attribute where cat_id=? and attr_id=?"
                db.query(sql, [id, attrId], (err, data) => {
                    return res.ResData('更新成功', 200, {
                        "attr_id": attrId,
                        "attr_name": attrName,
                        "cat_id": id,
                        "attr_sel": attrSel,
                        "attr_write": data[0].attr_write,
                    })
                })
            })
        } else {
            var sql = "update sp_attribute set attr_name=?,attr_sel=?,attr_vals=?where cat_id=? AND attr_id=?"
            db.query(sql, [attrName, attrSel, attrVals, id, attrId], (err, result) => {
                if (err) return res.ResData('更新失败')
                if (result.affectedRows < 1) {
                    return res.ResData('更新失败')
                }
                var sql = "select * from sp_attribute where cat_id=? and attr_id=?"
                db.query(sql, [id, attrId], (err, data) => {
                    return res.ResData('更新成功', 200, {
                        "attr_id": attrId,
                        "attr_name": attrName,
                        "cat_id": id,
                        "attr_sel": attrSel,
                        "attr_write": data[0].attr_write,
                        "attr_vals": attrVals
                    })
                })
            })
        }


    }
    // 参数列表
exports.getAttributes = (req, res) => {
        // console.log(132);
        var id = req.params.id
        var attrSel = req.query.sel
        var sql = "select * from sp_attribute where cat_id=?"
        db.query(sql, id, (err, result) => {
            if (err) return res.ResData('获取参数列表失败！')
                // console.log(result[0]);
            if (attrSel == 'only') {
                var arr = []
                for (idx in result) {
                    if (result[idx].attr_sel == 'only') {
                        arr.push({
                            "attr_id": result[idx].attr_id,
                            "attr_name": result[idx].attr_name,
                            "cat_id": result[idx].cat_id,
                            "attr_sel": result[idx].attr_sel,
                            "attr_write": result[idx].attr_write,
                            "attr_vals": result[idx].attr_vals
                        })
                    }
                }
            } else {
                var arr = []
                for (idx in result) {
                    if (result[idx].attr_sel == 'many') {
                        arr.push({
                            "attr_id": result[idx].attr_id,
                            "attr_name": result[idx].attr_name,
                            "cat_id": result[idx].cat_id,
                            "attr_sel": result[idx].attr_sel,
                            "attr_write": result[idx].attr_write,
                            "attr_vals": result[idx].attr_vals
                        })
                    }
                }
            }
            res.ResData('获取成功', 200, arr)
        })
    }
    // 添加动态参数或者静态属性
exports.addAttributes = (req, res) => {
    // console.log(123);
    var id = req.params.id
    var attrName = req.body.attr_name
    var attrSel = req.body.attr_sel
    var attrVals = req.body.attr_vals
        // console.log(attrVals.length);
    if (!attrVals) {
        console.log(1);
    } else {
        console.log(2);
    }
    var sql = "select * from sp_attribute where attr_name=?"
    db.query(sql, attrName, (err, result) => {
        if (err) return res.ResData('添加失败')
        if (result.length > 0) {
            return res.ResData('参数已经存在')
        }
        if (!attrVals) {
            var sql = "INSERT INTO sp_attribute(attr_name,attr_sel,cat_id,attr_vals) VALUES(?,?,?,'') "
            db.query(sql, [attrName, attrSel, id], (err, data) => {
                if (err) return res.ResData('添加失败！')
                res.ResData("创建成功", 200, {
                    "attr_name": attrName,
                    "cat_id": id,
                    "attr_sel": attrSel,
                    "attr_vals": attrVals
                })
            })
        } else {
            var sql = "INSERT INTO sp_attribute(attr_name,attr_sel,cat_id,attr_vals) VALUES(?,?,?,?) "
            db.query(sql, [attrName, attrSel, id, attrVals], (err, data) => {
                if (err) return res.ResData('添加失败！')
                res.ResData("创建成功", 200, {
                    "attr_name": attrName,
                    "cat_id": id,
                    "attr_sel": attrSel,
                    "attr_vals": attrVals
                })
            })


        }

    })
}